import 'dart:convert';
import 'dart:math';

import 'package:base_flutter/base_flutter.dart';
// import 'package:esc_pos_bluetooth/esc_pos_bluetooth.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/src/widgets/framework.dart';
import 'package:ls_work/net/post_request.dart';
import 'package:ls_work/net/response/food/scan_old_data.dart';
import 'package:ls_work/print/sunmi_print_utils.dart';
import 'package:ls_work/res/resources.dart';
import 'package:ls_work/util/ext_utils.dart';
import 'package:ls_work/widgets/bottom_input_widget.dart';

import '../../message/message_config.dart';
import '../../net/response/food/week_menu_list_data.dart';

class WeekMenuViewModel extends BaseListViewModel<WeekMenuContent> {
  final String? siteId;
  final String? time;
  final String? orderModelType;
  final ScanOldData? oldData;
  final String? useType;

  WeekMenuViewModel(BuildContext context,
      {this.siteId, this.time, this.orderModelType, this.oldData, this.useType})
      : super(context);

  WeekMenuListData? menuData;

  double menuWidth = 100;

  var dateList = <String>[];

  // PrinterBluetoothManager printerManager = PrinterBluetoothManager();

  ///提取日期
  void requestDateList() {
    listItems.forEach((element) {
      element.ruleCategory?.forEach((type) {
        type.goodsInfo?.forEach((date) {
          var dateStr = getDate(date.weekDay??0);
          if (!dateList.contains(dateStr)) {
            dateList.add(dateStr);
          }
        });
      });
    });
    menuWidth = dateList.length * 180.3 + 110;
    print(menuWidth);
  }

  @override
  Future<List<WeekMenuContent>> requestListData() async {
    var data = await PostRequest.weekMenu(
        time, siteId, oldData?.selectOldId.toString(), orderModelType);
    if ('0' == data['code'].toString()) {
      if (data['data'] != null) {
        menuData = WeekMenuListData.fromJson(data['data']);
        menuData?.menuJson?.content?.forEach((time) {
          time.ruleCategory?.forEach((type) {
            type.goodsInfo?.forEach((date) {
              var foodLength = date.goodsList?.length ?? 0;
              date.maxnumber = type.selectNumber;
              // date.foodLength = max(foodLength, date.foodLength??0);
              date.timeTypeId = time.timeSection.toString();
              type.foodLength = max(foodLength, type.foodLength??0);
              date.weekDate = getDateValue(date.weekDay??0);
              date.goodsList?.forEach((food) {
                if (food.status == 1) {
                  date.selectItems.add(food);
                }
                // food.foodDate = getDate(date.weekDay);
                // food.oldStatus = food.status;
                // food.oldNumber = food.number;
                // food.foodEndTime = time.endTime ?? "";
                // food.canSelect = canSelect(food);
              });
            });
            if(time.foodLength==null){
              time.foodLength = 0;
            }
            time.foodLength = time.foodLength!+(type.foodLength??0);
          });
        });
        return menuData?.menuJson?.content??[];
      } else {
        throw '未获取到周菜单';
      }
    } else {
      throw data['msg'];
    }
  }


  String getDate(int weekDay) {

    return getDateValue(weekDay)?.toDateStr([yyyy, '-', mm, '-', dd])??"";
  }

  DateTime? getDateValue(int weekDay) {
    DateTime? monday;
    if (time == '1') {
      var now = DateTime.now();
      monday = now.add(Duration(days: -1 * now.weekday + 1));
    }

    if (time == '2') {
      var now = DateTime.now();
      monday = now.add(Duration(days: 7 - now.weekday + 1));
    }

    if (time == '3') {
      var now = DateTime.now();
      monday = now.add(Duration(days: 7 - now.weekday + 7 + 1));
    }

    var date = monday?.add(Duration(days: weekDay - 1));

    return date;
  }

  bool canSelect(GoodsList food) {
    // if(food.flag??false){
    if (food.foodEndTime.isNullOrEmpty()) {
      var now = DateTime.now();
      var today = now.toDateStr([yyyy, '-', mm, '-', dd]);
      var foodDate = DateTime.parse('${food.foodDate} 00:00:00');
      var nowTime = DateTime.parse('${today} 00:00:00');
      if (foodDate.isBefore(nowTime)) {
        return false;
      }
      if(1==food.isTake){
        return false;
      }else{
        return true;
      }
    } else {
      var now = DateTime.now();
      var today = now.toDateStr([yyyy, '-', mm, '-', dd]);
      var foodDate = DateTime.parse('${food.foodDate} 00:00:00');
      var nowTime = DateTime.parse('${today} 00:00:00');
      if (foodDate.isBefore(nowTime)) {
        return false;
      }
      if (food.foodDate == today) {
        var endTime = DateTime.parse('${today} ${food.foodEndTime}');
        print("endTime===>${food.foodEndTime}");
        if (now.isAfter(endTime)) {
          return false;
        } else {
          if(1==food.isTake){
            return false;
          }else{
            return true;
          }
        }
      } else {
        if(1==food.isTake){
          return false;
        }else{
          return true;
        }
      }
    }
    // }else{
    //   return false;
    // }
  }

  ///listView滑动监听
  ScrollController horizontalScrollController = ScrollController();
  ScrollController verticalScrollController = ScrollController();
  ScrollController verticalTypeScrollController = ScrollController();

  Widget menuContent() {
    requestDateList();
    return Stack(
      children: [
        ListView(
          children: [
            Column(
              children: [
                Row(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: datesWidgetList(),
                ),
                ListView(
                  controller: verticalScrollController,
                  children: listItems.map((e) {
                    return Column(
                      children: [
                        Row(
                          children: [
                            ///用餐时段
                            CommonText(e.timeStr ?? "").addToContainer(
                              width: 50,
                              height: 50 * (e.foodLength??=0).toDouble(),
                              alignment: Alignment.center,
                              decoration: BoxDecoration(
                                  color: Colors.white,
                                  border: Border.all(width: 0.3)),
                            ),

                            ///菜品类型
                            Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: (e.ruleCategory ?? []).map((type) {
                                return Row(
                                  children: [
                                    CommonText(
                                            "${type.categary}\n(选${type.selectNumber})",
                                            textAlign: TextAlign.center)
                                        .addToContainer(
                                            width: 60,
                                            height: (50 * (type.foodLength??0))
                                                .toDouble(),
                                            alignment: Alignment.center,
                                            decoration: BoxDecoration(
                                                color: Colors.white,
                                                border:
                                                    Border.all(width: 0.3))),
                                    Row(
                                      mainAxisAlignment:
                                          MainAxisAlignment.start,
                                      crossAxisAlignment:
                                          CrossAxisAlignment.start,
                                      children:
                                          (type.goodsInfo ?? []).map((date) {
                                        return (date.goodsList??[]).isEmpty
                                            ? Container(
                                                width: 180,
                                                decoration: BoxDecoration(
                                                  color: Colors.white,
                                                  // border: Border.all(width: 0.3,color: Colors.grey),
                                                ),
                                              )
                                            : Column(
                                                mainAxisAlignment:
                                                    MainAxisAlignment.start,
                                                children: (date.goodsList ?? [])
                                                    .map((food) {
                                                  return Row(
                                                    children: [
                                                      CommonText(
                                                              food.goodsName ??
                                                                  "")
                                                          .setWeight(1),
                                                      food.canSelect&&1!=food.isTake
                                                          ? Checkbox(
                                                              value:
                                                                  food.selected,
                                                              onChanged:
                                                                  (value) {
                                                                selectFood(food,
                                                                    date, type);
                                                              })
                                                          : Container()
                                                    ],
                                                  ).onTap(() {
                                                    selectFood(
                                                        food, date, type);
                                                  }).addToContainer(
                                                      width: 180,
                                                      height: 50,
                                                      decoration: BoxDecoration(
                                                          color: Colors.white,
                                                          border: Border.all(
                                                              width: 0.3)),
                                                      alignment:
                                                          Alignment.centerLeft,
                                                      padding:
                                                          EdgeInsets.symmetric(
                                                              horizontal: 5));
                                                }).toList(),
                                              );
                                      }).toList(),
                                    )
                                  ],
                                );
                              }).toList(),
                            ).addToContainer(
                                decoration: BoxDecoration(
                                    color: Colors.white,
                                    border: Border.all(width: 0.3))),
                          ],
                        ),
                        Container(
                          height: 0.4,
                          color: Colors.black,
                        ),
                      ],
                    );
                  }).toList(),
                ).addToContainer(width: menuWidth).setWeight(1)
              ],
            )
          ],
          scrollDirection: Axis.horizontal,
          controller: horizontalScrollController,
          padding: EdgeInsets.all(0),
        )
      ],
    ).addToContainer(width: menuWidth);
  }

  ///头部日期显示
  List<Widget> datesWidgetList() {
    var widgetList = dateList.map((e) {
      return CommonText(e).addToContainer(
          width: 180,
          height: 50,
          alignment: Alignment.center,
          decoration: BoxDecoration(
              color: Colors.white, border: Border.all(width: 0.3)));
    }).toList();
    widgetList.insertAll(0, [
      CommonText('日期').addToContainer(
          height: 50,
          width: 48.5,
          alignment: Alignment.center,
          decoration: BoxDecoration(
              color: Colors.white, border: Border.all(width: 0.3))),
      Container(
          width: 60,
          height: 50,
          decoration: BoxDecoration(
              color: Colors.white, border: Border.all(width: 0.3)))
    ]);

    return widgetList;
  }

  Future<void> submitWeek() async {
    // print(older.selectOldId);
    // return;
    var foodDateList = <GoodsInfo>[];
    listItems.forEach((time) {
      time.ruleCategory?.forEach((type) {
        type.goodsInfo?.forEach((date) {
          if (date.selectItems.isNotEmpty) {
            foodDateList.add(date);
          }
        });
      });
    });

    if (foodDateList.isEmpty) {
      showToast('请选择菜品');
      return;
    }

    showBottomInputWidget();
  }

  Future<void> submitRequest(String remark) async {
    var finish = false;
    var content = listItems.map((e) => e.toSubmitJson()).toList();
    calculatePrice();

    showLoadingDialog();
    try {
      var data = await PostRequest.submitWeekOrder(
          menuData?.menuId.toString(),
          menuData?.menuJson?.weekMenuModel.toString(),
          siteId,
          oldData?.selectOldId.toString(),
          time,
          orderModelType,
          remark,
          content,
          menuData?.tenantId.toString(),
          menuData?.saasId.toString(),
          useType);
      hideDialog();
      if ('0' == data['code'].toString()) {
        var orderId = data['data']['id'].toString();
        // var totalMoney = data['data']['totalMoney'].toString();
        await payOrder(orderId, (totalPrice-oriPrice).toString());
      } else {
        showToast(data['msg']);
      }
    } catch (e) {
      hideDialog();
      showToast(NetErrorUtils.getNetError(e));
    }
  }

  Future<void> payOrder(String orderId, String totalMoney) async {
    showLoadingDialog(msg: '正在完成支付...');
    try {
      var data = await PostRequest.weekPayOrder(
          orderId: orderId, type: "2", totalMoney: totalMoney);
      hideDialog();
      if ('0' == data['code'].toString()) {
        showToast('支付成功');
        _printTicket();
        sendMessage(SendMessageEvent(MessageConfig.PAY_FOOD_SUCCESS));
        finish();
      } else {
        showToast(data['msg']);
      }
    } catch (e) {
      hideDialog();
      showToast(NetErrorUtils.getNetError(e));
    }
  }

  void _printTicket() {
    var printData = listItems.toPrintData(dateList[0]);
    SunmiPrinterUtils.printWeekOrder(
        oldData?.elderHumanName??"", oldData?.elderHumanRoom ?? "", printData);
  }

  void showBottomInputWidget() {
    showBottomInput(context, title: '备注', hint: '请输入备注信息',
        onSubmit: (str) async {
      // finish();
      await submitRequest(str);
    });
  }

  @override
  void onCreated() {
    super.onCreated();
    requestRefresh();
    // _initBluetoothPrinter();
    verticalScrollController.addListener(() {
      var top = verticalScrollController.offset;
      if (verticalTypeScrollController.positions.isNotEmpty) {
        verticalTypeScrollController.jumpTo(
          top,
        );
      }
    });
  }

  // void _initBluetoothPrinter() {
  //   printerManager.scanResults.listen((printers) async {
  //     // store found printers
  //     var list = printers.map((e) => e.name).toList();
  //     print(list);
  //   });
  //
  //   printerManager.startScan(Duration(seconds: 4));
  // }

  void selectFood(GoodsList food, GoodsInfo date, RuleCategory type) {
    if (date.selectItems.contains(food)) {
      date.selectItems.remove(food);
      food.selected = false;
      food.number = 0;
    } else {
      if (date.selectItems.length >= (date.maxnumber??0)) {
        if (1 == date.maxnumber) {
          for (var food in date.selectItems) {
            food.selected = false;
            food.number = 0;
          }
          date.selectItems.clear();
          date.selectItems.add(food);
          food.selected = true;
          food.number = 1;
        } else {
          showToast('${type.categary}最多选择${type.selectNumber}个菜品');
        }
      } else {
        date.selectItems.add(food);
        food.selected = true;
        food.number = 1;
      }
    }
    notifyListeners();
  }

  @override
  void dispose() {
    horizontalScrollController.dispose();
    verticalTypeScrollController.dispose();
    verticalScrollController.dispose();
    super.dispose();
  }

  var totalPrice = 0.0;
  var oriPrice = 0.0;
  void calculatePrice(){
    var total = 0.0;
    var ori = 0.0;
    menuData?.menuJson?.content?.forEach((time) {
      time.ruleCategory?.forEach((type) {
        type.goodsInfo?.forEach((date) {
          date.goodsList?.forEach((food) {
            if(food.canSelect&&1!=food.isTake){
              total+=(food.price??0)*(food.number??0);
            }
            if(1==food.oldStatus){
              ori+=((food.price??0)*(food.oldNumber??0));
            }
          });
        });
      });
    });
    totalPrice = total;
    oriPrice = ori;
  }
}
